package com.yifushidai.api;

import com.yifushidai.entity.ApkEntity;
import com.yifushidai.mapper.ApkEntityMapper;
import com.yifushidai.qrcode.QRCodeUtil;
import com.yifushidai.utils.ErrorCodeEnum;
import com.yifushidai.utils.R;
import com.yifushidai.utils.UUIDUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

@RestController
@Api(tags = "安卓APK")
@RequestMapping("/api/apk")
public class ApkController {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private ApkEntityMapper apkMapper;

    @PostMapping("/upload")
    @ApiOperation(value = "单文件上传apk接口", notes = "单文件上传apk", produces = MediaType.APPLICATION_JSON_VALUE)
    public R upload(@ApiParam(value = "apk文件流", required = true) @RequestParam("file") MultipartFile file,
                    @ApiParam(value = "版本号", required = true) @RequestParam("version") String version,
                    @ApiParam(value = "更新内容", required = true) @RequestParam("desc") String desc,
                    HttpServletRequest request) throws Exception {
        if (!version.matches("^\\d+\\.\\d+\\.\\d+$")) {
            return R.error(ErrorCodeEnum.ARGUMENT_VALIDATION);
        }

//        String apkPath = request.getSession().getServletContext().getRealPath("fileStore" + File.separator + "apkDirectory");//物理路径
//        String qrPath = request.getSession().getServletContext().getRealPath("fileStore" + File.separator + "qrDirectory");//物理路径
//        String basePath = "https://" + request.getServerName() + request.getContextPath();//获取的服务器地址

        String classPath = "/data/wwwroot/" + request.getServerName();
        String apkPath = classPath + "/fileStore/apkDirectory";//物理路径
        String qrPath = classPath + "/fileStore/qrDirectory";//物理路径
        String basePath = request.getScheme() + "://" + request.getServerName() + request.getContextPath();//获取的服务器地址

        String uploadFilename = file.getOriginalFilename();
        int index = uploadFilename.lastIndexOf(".");
        if (index < 0 || !uploadFilename.substring(index).equalsIgnoreCase(".apk")) {
            return R.error(ErrorCodeEnum.FILE_UPLOAD_FAIL).put(uploadFilename + " 请上传apk类型文件");
        }
//        String filename = uploadFilename.substring(0, index) + "_" + UUIDUtils.creatUUID() + uploadFilename.substring(index);
        String filename = "app-release_2170c982ac3746479e4c7e52cdb9867c.apk";//v3.1.5
        file.transferTo(new File(apkPath, filename));

        String apkUrl = basePath + "/fileStore/apkDirectory/" + filename;
        BufferedImage bi = ImageIO.read(new File(qrPath + "/512x512.png"));
        String qrName = filename.replaceAll("\\.\\w+$", "\\.jpg");
        // 生成二维码
        QRCodeUtil.encode(apkUrl, bi, null, qrName, qrPath, true);
        String qrUrl = basePath + "/fileStore/qrDirectory/" + qrName;

        ApkEntity apkEntity = new ApkEntity();
        apkEntity.setVersion(version);
        apkEntity.setUpdateDesc(desc);
        apkEntity.setApkUrl(apkUrl);
        apkEntity.setQrUrl(qrUrl);
        if (apkMapper.insertSelective(apkEntity) > 0) {
            return R.ok().put(apkEntity);
        } else {
            return R.error(ErrorCodeEnum.DATASOURCE_ERROR);
        }

    }

    @PostMapping(value = "/uploadMore")
    @ApiOperation(value = "多文件上传apk接口", notes = "多文件上传apk", produces = MediaType.APPLICATION_JSON_VALUE)
    public R uploadMore(HttpServletRequest request1) throws Exception {
        MultipartHttpServletRequest request = (MultipartHttpServletRequest) request1;
//        String apkPath = request.getSession().getServletContext().getRealPath("fileStore" + File.separator + "apkDirectory");//物理路径
//        String qrPath = request.getSession().getServletContext().getRealPath("fileStore" + File.separator + "qrDirectory");//物理路径
//        String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();//获取的服务器地址

        String classPath = "/data/wwwroot/" + request.getServerName();
        String apkPath = classPath + "/fileStore/apkDirectory";//物理路径
        String qrPath = classPath + "/fileStore/qrDirectory";//物理路径
        String basePath = request.getScheme() + "://" + request.getServerName() + request.getContextPath();//获取的服务器地址

        List<String> urlList = new ArrayList<>();
        List<MultipartFile> files = request.getFiles("file");
        for (MultipartFile file : files) {
            String uploadFilename = file.getOriginalFilename();
            int index = uploadFilename.lastIndexOf(".");
            if (index < 0 || !uploadFilename.substring(index).equalsIgnoreCase(".apk")) {
                urlList.add(uploadFilename + " 文件名非法");
                continue;
            }
            String filename = uploadFilename.substring(0, index) + "_" + UUIDUtils.creatUUID() + uploadFilename.substring(index);
            file.transferTo(new File(apkPath, filename));

            String apkUrl = basePath + "/fileStore/apkDirectory/" + filename;
            BufferedImage bi = ImageIO.read(new File(qrPath + "/512x512.png"));
            String qrName = filename.replaceAll("\\.\\w+$", "\\.jpg");
            // 生成二维码
            QRCodeUtil.encode(apkUrl, bi, null, qrName, qrPath, true);
            String qrUrl = basePath + "/fileStore/qrDirectory/" + qrName;

            urlList.add(qrUrl);
        }
        return R.ok().put(urlList);
    }

    @PostMapping("/download")
    @ApiOperation(value = "下载apk接口", notes = "下载apk", produces = MediaType.APPLICATION_JSON_VALUE)
    public R download(@ApiParam(value = "版本号", required = true) @RequestParam("version") String version) {
        if (!version.matches("^\\d+\\.\\d+\\.\\d+$")) {
            return R.error(ErrorCodeEnum.ARGUMENT_VALIDATION);
        }
        ApkEntity apkEntity = apkMapper.selectNewest();
        if (!version.equals(apkEntity.getVersion())) {
            return R.ok().put(apkEntity);
        } else {
            return R.error(ErrorCodeEnum.APK_NEWEST_ERROR);
        }
    }

}
